package fw_middleware

import (
	"errors"
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
	"transport/framework/fw_jwt"
)

func JwtAuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 获取authorization header
		tokenString := c.GetHeader("Authorization")
		// 获取真正的token字符串
		tokenStringArr := strings.Split(tokenString, " ")
		if len(tokenStringArr) != 2 || tokenStringArr[0] != "Bearer" || tokenStringArr[1] == "" || tokenStringArr[1] == "undefined" {
			c.AbortWithStatusJSON(http.StatusUnauthorized, errors.New("未携带token"))
			return
		}
		// 解析认证数据
		claimsData, err := fw_jwt.ParseJwt(tokenStringArr[1])
		if err != nil {
			c.AbortWithStatusJSON(http.StatusUnauthorized, err.Error())
			return
		}
		// 如果存在
		c.Set("jwtInfo", claimsData)
		c.Next()
	}
}
